package com.taoshen.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.taoshen.util.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Description
 * @Author Zhang Litao
 * @Date 2021/11/18 13:15
 */
public class JWTTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> resultMap = MapUtil.newHashMap();

        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
            resultMap.put("msg", "token未携带！");
            resultMap.put("code", "500");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(JSONUtil.toJsonStr(resultMap));
            return false;
        }

        try {
            JWTUtils.verifyToken(token);
            return true;
        } catch (SignatureVerificationException e) {
            resultMap.put("msg", "签名不一致异常");
        } catch (TokenExpiredException e) {
            resultMap.put("msg", "token过期异常");
        } catch (AlgorithmMismatchException e) {
            resultMap.put("msg", "算法不匹配异常");
        } catch (InvalidClaimException e) {
            resultMap.put("msg", "失效的payload异常");
        } catch (Exception e) {
            resultMap.put("msg", "token校验失败");
        }

        resultMap.put("code", "500");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(JSONUtil.toJsonStr(resultMap));
        return false;
    }
}